﻿/****************************************************************
*   作者：Morain
*   创建时间：2018/2/27 19:07:10
*   描述说明：
*****************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace ETSModel
{
  public class Hotfix : Entity
  {
#if ILRuntime
    private ILRuntime.Runtime.Enviorment.AppDomain appDomain;
#else
    private Assembly assembly;
#endif
    private IStaticMethod start;
    public Action Update;
    public Action LateUpdate;
    public Action OnApplicationQuit;

    public void GotoHotfix()
    {
#if ILRuntime // IL一些初始化
      ILHelper.InitILRuntime(this.appDomain);
#endif
      this.start.Run();
    }

    public void LoadHotfixAssembly()
    {
      GameObject codeGameObject = Resources.Load<GameObject>("Code");
      byte[] dllBytes = codeGameObject.Get<TextAsset>("Hotfix.dll").bytes;

#if ILRuntime
      this.appDomain = new ILRuntime.Runtime.Enviorment.AppDomain();
      byte[] pdbBytes = codeGameObject.Get<TextAsset>("Hotfix.pdb").bytes;
      using (MemoryStream ms = new MemoryStream(dllBytes))
      {
        using (MemoryStream p = new MemoryStream(pdbBytes))
        {
          this.appDomain.LoadAssembly(ms, p, new Mono.Cecil.Pdb.PdbReaderProvider());
        }
      }
      this.start = new ILStaticMethod(this.appDomain, "Hotfix.Init", "Start", 0);
#else
      byte[] mdbBytes = codeGameObject.Get<TextAsset>("Hotfix.mdb").bytes;
      this.assembly = Assembly.Load(dllBytes, mdbBytes);
      this.start = new MonoStaticMethod(this.assembly.GetType("Hotfix.Init"), "Start");
#endif
    }
  }
}